package com.tarena.mvc.service;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.tarena.mvc.domain.Product;
import com.tarena.mvc.util.HbnUtil;

public class ProductDao {

	/**
	 * @InsertProduct
	 * @param product
	 */
	public void InsertProduct(Product product) {
		Session s = HbnUtil.getSession();
		try {
			s.beginTransaction();
			s.save(product);
			s.getTransaction().commit();
		} catch (HibernateException e) {
			s.getTransaction().rollback();
			e.printStackTrace();
		}
		s.close();
	}

	/**
	 * @delete Product
	 * @param productId
	 * @description becuse user
	 */
	public void deleteProductsById(int[] productIds) {
		Session s = HbnUtil.getSession();
		try {
			s.beginTransaction();
			for (int i = 0; i < productIds.length; i++) {
				 s.delete(s.get(Product.class, productIds[i]));
			}
			s.getTransaction().commit();
		} catch (HibernateException e) {
			s.getTransaction().rollback();
		} finally {
			s.close();
		}
	}

	/**
	 * @Get product
	 * @return list
	 */
	public List<Product> getProduct() {
		Session s = HbnUtil.getSession();
		Query query = s.createQuery("from Product");
		List<Product> productList = query.list();
		return productList;
	}

	/**
	 * @getProductById
	 * @param productId
	 * @return
	 */
	public Product getProductById(int productId) {
		Session s = HbnUtil.getSession();
		Product product = (Product) s.get(Product.class, productId);
		return product;
	}
	
	/**
	 * @update a product
	 * @param product
	 */
	public void updateProduct(Product product) {
		Session s = HbnUtil.getSession();
		try {
			s.beginTransaction();
			s.update(product);
			s.getTransaction().commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			s.getTransaction().rollback();
		} finally {
			s.close();
		}
	}

}
